<template>
  <div>
    <PerfectTableComponent
      :loadTableList="loadTableList"
      :changePageSize="changePageSize"
      :changePage="changePage"
      :removeQueryField="removeQueryField"
      :clearQuery="clearQuery"
      v-model:query="query"
      title="角色"
      ref="tableRef"
      :queryFormHeaders="queryFormHeaders"
      :table="table"
      :tableColumns="tableColumns"
      :showTableIndex="false"
      :operatorColumnWidth="300"
      :baseUrl="urls.API_URL_BACKSTAGE_ROLE_MANAGE"
      v-model:multipleSelection="multipleSelection"
      v-model:form="form"
      :formRules="formRules"
      :formHeader="formHeader"
      @beforeAddRow="beforeAddRow"
    >
      <!-- 查询表单自定义元素,下面用于调试，也可以用于范例 -->
      <!-- <template #query_form__name="scope">
        <el-input
          v-model="query['name']"
          :style="`width:${scope.item.width ? scope.item.width : '200px'}`"
          :placeholder="`${scope.item.placeholder ? scope.item.placeholder : scope.item.label}`"
          clearable
        />
      </template> -->
      <!-----------------------------表格左侧工具栏的右侧----------------------------------------->
      <template #toorbar_left_right>
        <el-button
          :disabled="multipleSelection.length === 0"
          icon="circle-close"
          type="warning"
          style="margin: 0 5px 0 0"
          @click="updateRoleEnabled(false)"
          >停用角色</el-button
        >
        <el-button
          :disabled="!multipleSelection.length"
          icon="circle-close"
          type="success"
          style="margin: 0 5px 0 0"
          @click="updateRoleEnabled(true)"
          >启用角色</el-button
        >
      </template>
      <!-----------------------------表格自定义操作列----------------------------------------->
      <!--表格操作列右侧添加-->
      <template #table_operator_right="scope">
        <el-button type="primary" size="small" icon="edit" plain @click="permissionManage(scope.row)"
          >分配菜单</el-button
        >
      </template>
      <!-----------------------------表格自定义列----------------------------------------->
      <!--默认角色-->
      <template #table_column_defaultRole="scope: any">
        <el-tag :type="`${scope.row.defaultRole == true ? 'success' : 'info'}`">{{
          dictToMap(yesOrNoDict).get(scope.row.defaultRole)
        }}</el-tag>
      </template>
      <!--启用状态-->
      <template #table_column_enabled="scope: any">
        <el-switch
          v-model="scope.row.enabled"
          :loading="scope.row.loading"
          @change="enabledChange($event, scope.row)"
          inline-prompt
          active-icon="Check"
          inactive-icon="Close"
        />
      </template>
    </PerfectTableComponent>
    <!--角色权限菜单-->
    <RolePermissionManage ref="rolePermissionDialogRef" :loadTableList="loadTableList" />
  </div>
</template>

<script lang="ts" setup>
import PerfectTableComponent from '@/components/base/table/PerfectTableComponent.vue';
import RolePermissionManage from '@/views/page/authority/rolemanage/RolePermissionManage.vue';
import { provide, reactive, ref } from 'vue';
import useTableList from '@/api/hooks/useTableList';
import type { FormHeader, ResponseData, TableColumn } from '@/types/interface/base_interface';
import type { Role } from '@/types/interface/auth_interface';
import Request from '@/api/request/request';
import urls from '@/api/request/urls';
import { yesOrNoDict, dictToMap } from '@/api/dict';
import { ElMessage } from 'element-plus';

// 表格工具必备参数
const { table, query, loadTableList, removeQueryField, clearQuery, changePageSize, changePage } = useTableList(
  urls.API_URL_BACKSTAGE_ROLE_MANAGE
);

// 将表格刷新函数传到子容器
provide('loadTableList', loadTableList);

//查询==========================================================
const queryFormHeaders = ref<FormHeader[]>([
  // 查询表单
  {
    prop: 'name',
    label: '角色标识'
  },
  {
    prop: 'nameZh',
    label: '角色名称'
  },
  {
    prop: 'enabled',
    label: '启用状态',
    type: 'select',
    list: yesOrNoDict,
    width: '197px'
  },
  {
    prop: 'defaultRole',
    label: '默认角色',
    type: 'select',
    list: yesOrNoDict,
    show: false,
    width: '197px'
  }
]);

//表格==========================================================
// 表格插件ref对象
const tableRef = ref();

//表格列
// 定义表格所有的列字段信息
const tableColumns = ref<TableColumn[]>([
  {
    label: '角色名称',
    prop: 'nameZh',
    fixed: true
  },
  {
    label: '角色标识',
    prop: 'name',
    width: 150
  },
  {
    label: '默认角色',
    prop: 'defaultRole',
    width: 100,
    type: 'dict',
    dict: yesOrNoDict
  },
  {
    label: '级别',
    prop: 'level',
    width: 60
  },
  {
    label: '启用状态',
    prop: 'enabled',
    width: 100,
    type: 'custom'
  },
  {
    label: '使用账户',
    prop: 'userNumber',
    width: 100
  },
  {
    label: '权限数量',
    prop: 'permissionumber',
    width: 100
  },
  {
    label: '创建时间',
    prop: 'createTime',
    width: 180
  }
]);

//定义表格复选框。注意非必填字段
const multipleSelection = ref<Role[]>([]); // 复选框选择的记录row
// 更改角色的可用状态
const enabledChange = async (newVal: boolean, row: Role) => {
  const ids = [row.id]; // 定义批量操作的角色主键
  const updateForm = {
    ids,
    enabled: newVal
  };
  row.loading = true; // 加载中
  const resData: ResponseData = await new Request(
    urls.API_URL_BACKSTAGE_ROLE_STOP_ENABLED,
    JSON.stringify(updateForm)
  ).patch();
  row.loading = false; // 加载结束
  if (resData.success) {
    // 如果操作成功
    let message = `已停用${row.nameZh}`;
    if (newVal) {
      message = `已启用${row.nameZh}`;
    }
    ElMessage.success(message);
  } else {
    // 如果失败
    row.enabled = !newVal; // 恢复原来的值
  }
};
// 点击停用角色按钮
const updateRoleEnabled = async (enabled: boolean) => {
  if (multipleSelection.value.length > 0) {
    const ids: string[] = []; // 定义批量操作的角色主键
    for (let i = 0; i < multipleSelection.value.length; i += 1) {
      const item: Role = multipleSelection.value[i];
      ids.push(item.id!.toString());
    }
    const updateForm = {
      ids,
      enabled
    };
    const resData = await new Request(urls.API_URL_BACKSTAGE_ROLE_STOP_ENABLED, JSON.stringify(updateForm)).patch();
    if (resData.success) {
      ElMessage.success('操作成功');
      loadTableList(); // 刷新表格
    }
  } else {
    ElMessage.error('请至少选择一条数据');
  }
};
// 菜单分配处理
const rolePermissionDialogRef = ref(); // 分配菜单对话框
// 当点击分配菜单时
const permissionManage = (role: Role) => {
  rolePermissionDialogRef.value.openDialog(role);
};

//表单==========================================================
//表单对象
const form = ref<Role>({});
//表单元素类型
const formHeader = ref<FormHeader[]>([
  {
    label: '角色名称',
    prop: 'nameZh'
  },
  {
    label: '角色标识',
    prop: 'name'
  },
  {
    label: '级别',
    prop: 'level',
    type: 'number',
    rules: [{ type: 'number', message: '请输入数字类型' }]
  },
  {
    label: '默认角色',
    prop: 'defaultRole',
    type: 'switch'
  },
  {
    label: '启用状态',
    prop: 'enabled',
    type: 'switch'
  },
  {
    label: '描述',
    prop: 'description',
    placeholder: '请输入角色的描述',
    type: 'textarea'
  }
]);
//表单验证规则，用于全局表单验证
const formRules = reactive({
  nameZh: [
    {
      required: true,
      message: '不能为空',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度必须在2-20个字符之间',
      trigger: 'blur'
    }
  ],
  name: [
    {
      required: true,
      message: '不能为空',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '必须在2-20个字符之间',
      trigger: 'blur'
    }
  ],
  level: [
    {
      required: true,
      message: '不能为空',
      trigger: 'blur'
    }
  ]
});
//在添加行的动作以前
const beforeAddRow = async () => {
  //传入初始值
  form.value = {
    level: 100,
    defaultRole: false,
    enabled: true
  };
};
// 点击添加角色按钮
// const addRow = () => {
//   const form = {
//     level: 100,
//     defaultRole: false,
//     enabled: true
//   };
//   action.value = 'post';
//   dialogRef.value!.openDialog(form);
// };

// 编辑单行记录。
// const editRow = async (row: Role) => {
//   action.value = 'put';
//   // 读取账户信息
//   const resData: ResponseData = await new Request(`${urls.API_URL_BACKSTAGE_ROLE_MANAGE}/${row.id}`).get();
//   if (resData.success) {
//     const form = resData.data;
//     // dialogRef.value!.openDialog(JSON.parse(JSON.stringify(form)));
//     dialogRef.value!.openDialog(form);
//   }
// };
</script>
<style lang="scss" scoped></style>
